package com.sjc.designpattern.strategy;

import com.sjc.designpattern.proxy.ProxyPatternDemo;

/**
 * @Classname StrategryPatternDemo
 * @Description 策略模式：替换掉屎一样的if else语句
 * @Date 2020/4/26 09:42
 * @Created by SangJiacun
 */
public class StrategryPatternDemo {
    public static void main(String[] args) {
        int discountStyle = 1;

        DiscountCalculateStrategy discountCalculateStartegy = DiscountCalculateStrategyFactory.getDiscountCalculateStartegy(discountStyle);
        //discountCalculateStartegy.calculate();//执行优惠计价方式1的复杂业务逻辑

        Context context = new Context();
        context.setStrategy(discountCalculateStartegy);
        context.claculate();//执行优惠计价方式1的复杂业务逻辑

        // 要点1：必须将if else的代码，封装到不同的策略类中
        // 要点2：将选择哪种策略的逻辑给放到一个工厂类中去，选择策略的代码务必很简洁
        // 要点3：context可有可无，具体是看你的策略执行逻辑，如果就几行代码，不需要context
        // 如果context中的策略执行逻辑较为复杂一点，context来封装策略类的执行逻辑
    }


    public static class DiscountCalculateStrategyFactory{
        public static DiscountCalculateStrategy getDiscountCalculateStartegy(int discountStyle){
            if(1 == discountStyle){
                return new DiscountCalculateStrategyA();
            }else if(2 == discountStyle){
                return new DiscountCalculateStrategyB();
            }else if(3 == discountStyle){
                return new DiscountCalculateStrategyC();
            }else{
                return new DiscountCalculateStrategyDefault();
            }
        }
    }

    public static class Context{
        private DiscountCalculateStrategy strategy;

        public DiscountCalculateStrategy getStrategy() {
            return strategy;
        }

        public void setStrategy(DiscountCalculateStrategy strategy) {
            this.strategy = strategy;
        }

        public void claculate(){
            strategy.calculate();
        }
    }

    public interface DiscountCalculateStrategy{
        void calculate();
    }

    public static class DiscountCalculateStrategyA implements  DiscountCalculateStrategy{
        @Override
        public void calculate() {
            System.out.println("执行优惠计价方式1的复杂业务逻辑");
        }
    }

    public static class DiscountCalculateStrategyB implements  DiscountCalculateStrategy{
        @Override
        public void calculate() {
            System.out.println("执行优惠计价方式2的复杂业务逻辑");
        }
    }

    public static class DiscountCalculateStrategyC implements  DiscountCalculateStrategy{
        @Override
        public void calculate() {
            System.out.println("执行优惠计价方式3的复杂业务逻辑");
        }
    }

    public static class DiscountCalculateStrategyDefault implements  DiscountCalculateStrategy{
        @Override
        public void calculate() {
            System.out.println("执行默认的优惠计价方式的复杂业务逻辑");
        }
    }
}
